﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MESQWinform;
using Ces.Entity;
using Newtonsoft.Json;
using System.IO;

namespace MesProjectWinform.BasicData.基础实现.显示页面
{
    public partial class jianCreate : DevExpress.XtraEditors.XtraForm
    {
        // 定义一个委托和事件，用于通知父窗体刷新数据
        public delegate void DataAddedEventHandler();
        public event DataAddedEventHandler DataAdded;
        
        // 序号存储文件路径
        private readonly string sequenceFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WorkshopSequence.txt");
        // 日期格式化字符串
        private readonly string dateFormat = "yyMMdd";
        
        public jianCreate()
        {
            InitializeComponent();
            this.Load += JianCreate_Load;
        }
        
        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private void JianCreate_Load(object sender, EventArgs e)
        {
            // 设置车间编码文本框为只读
            bian.Properties.ReadOnly = true;
            // 生成自动递增编码
            GenerateAutoIncrementCode();
        }
        
        /// <summary>
        /// 生成自动递增的车间编码
        /// </summary>
        private void GenerateAutoIncrementCode()
        {
            try
            {
                // 生成当前日期部分 格式：yyMMdd
                string today = DateTime.Now.ToString(dateFormat);
                
                // 读取序号文件，获取当前最大序号
                int currentSequence = 1; // 默认从1开始
                string lastDate = string.Empty;
                
                if (File.Exists(sequenceFilePath))
                {
                    string[] fileContent = File.ReadAllLines(sequenceFilePath);
                    if (fileContent.Length >= 2)
                    {
                        lastDate = fileContent[0]; // 第一行存储日期
                        int.TryParse(fileContent[1], out currentSequence); // 第二行存储序号
                        
                        // 如果是新的一天，重置序号为1
                        if (lastDate != today)
                        {
                            currentSequence = 1;
                        }
                        // 注意：此处不自增序号，只显示当前序号
                    }
                }
                
                // 格式化为4位数字，前面补0
                string serialPart = currentSequence.ToString().PadLeft(4, '0');
                
                // 组合最终的编码：CJ + 日期 + 4位序号
                string finalCode = "CJ" + today + serialPart;
                
                // 设置到文本框
                bian.Text = finalCode;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"生成车间编码时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // 生成失败时使用默认编码
                bian.Text = "CJ" + DateTime.Now.ToString(dateFormat) + "0001";
            }
        }
        
        /// <summary>
        /// 保存成功后更新序号
        /// </summary>
        private void UpdateSequenceAfterSuccess()
        {
            try
            {
                // 获取当前日期
                string today = DateTime.Now.ToString(dateFormat);
                int currentSequence = 1;
                
                // 读取当前序号
                if (File.Exists(sequenceFilePath))
                {
                    string[] fileContent = File.ReadAllLines(sequenceFilePath);
                    if (fileContent.Length >= 2)
                    {
                        string lastDate = fileContent[0];
                        int.TryParse(fileContent[1], out currentSequence);
                        
                        // 如果是新的一天，重置序号为1
                        if (lastDate != today)
                        {
                            currentSequence = 1;
                        }
                        else
                        {
                            // 否则序号加1
                            currentSequence++;
                        }
                    }
                }
                
                // 保存更新后的序号到文件
                using (StreamWriter writer = new StreamWriter(sequenceFilePath, false))
                {
                    writer.WriteLine(today);
                    writer.WriteLine(currentSequence.ToString());
                }
            }
            catch (Exception ex)
            {
                // 更新序号失败不影响主流程，可以静默处理
                Console.WriteLine($"更新序号失败：{ex.Message}");
            }
        }
        
        /// <summary>
        /// 取消按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            // 重新生成自动递增编码
            GenerateAutoIncrementCode();
            
            // 清空其他输入框内容
            ming.Text = string.Empty;
            miao.Text = string.Empty;
        }
        /// <summary>
        /// 添加按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button2_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取输入的车间信息
                string workshopCode = bian.Text.Trim();
                string workshopName = ming.Text.Trim();
                string workshopDesc = miao.Text.Trim();
                // string workshopAttr = shuxing != null ? shuxing.Text.Trim() : null;
                
                // 创建车间对象
                WorkShop workshop = new WorkShop
                {
                    //id随时间生成
                   
                    
                    IsDeleted = false,
                    CreatedBy = "admin",
                    CreatedTime = DateTime.Now,
                    UpdatedBy = "张三",
                    UpdatedTime = DateTime.Now,

                    Workshopcode = workshopCode,
                    Workshopname = workshopName,
                    Workshopdescription = workshopDesc,
                    Workshopattributes = " ",
                };
                
                // 将对象序列化为JSON
                string postData = JsonConvert.SerializeObject(workshop);
                
                // 调用添加API
                string url = "api/WorkShop/AddWorkShop";
                string response = await APIClientl.CallApiAsync(url, "POST", postData);
                
                // 保存成功后更新序号
                UpdateSequenceAfterSuccess();
                
                // 触发数据添加事件，通知父窗体刷新数据
                DataAdded?.Invoke();
                
                // 关闭窗口
                this.Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"添加失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}